﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Bird.OAWeb.Domain.Table;
using Bird.OAWeb.EF; 
using System.Data;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using MySql.Data.MySqlClient;
using System.Data.SqlClient;

/// <summary>
/// Dapper实例（采用单例模式）
/// </summary>
public class DapperFactory
{
    /// <summary>
    /// 读取配置文件用
    /// </summary>
    private IConfiguration Configuration { get; set; }
    // 返回连接实例
    private static IDbConnection dbConnection = null;
    // 静态变量保存类的实例
    private static DapperFactory uniqueInstance;
    // 定义一个标识确保线程同步
    private static readonly object locker = new object();
    /// <summary>
    /// 私有构造方法，使外界不能创建该类的实例，以便实现单例模式
    /// </summary>
    private DapperFactory()
    {
        Configuration = new ConfigurationBuilder()
        .Add(new JsonConfigurationSource
        {
            Path = "appsettings.json",
            ReloadOnChange = true
        }).Build();
    }
    /// <summary>
    /// 获取实例，这里为单例模式，保证只存在一个实例
    /// </summary>
    /// <returns></returns>
    public static DapperFactory GetInstance()
    {
        // 双重锁定实现单例模式，在外层加个判空条件主要是为了减少加锁、释放锁的不必要的损
    if (uniqueInstance == null)
        {
            lock (locker)
            {
                if (uniqueInstance == null)
                {
                    uniqueInstance = new DapperFactory(); //懒汉模式
                }
            }
        }
        return uniqueInstance;
    }
    /// <summary>
    /// 创建数据库连接对象（采用了设计模式 之 工厂模式）
    /// </summary>
    /// <returns></returns>
    public IDbConnection GetDbConnection()
    {
        //如果数据库连接对象为空，则重新创建
        if (dbConnection == null)
        {
            //读取配置文件中的数据库服务器类型 mysql或sqlserver
            string dbType = Configuration["DbServerType"];
            //读取配置文件中的连接字符串
            string _connectionString =
            Configuration.GetConnectionString("Default");
            switch (dbType)
            {
                case "MySql":
                    dbConnection = new MySqlConnection(_connectionString);
                    break;
                case "SqlServer":
                    dbConnection = new MySqlConnection(_connectionString);
                    break;
            }
        }
        //判断连接状态（Dapper内部会自动打开数据库连接，所以无需以下下代码）
        //if (dbConnection.State == ConnectionState.Closed)
        //{
        // dbConnection.Open();
        //}
        return dbConnection;
    }
}